import axios from 'axios';
import { ElMessage } from 'element-plus';
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASE_URL,
  timeout: Number(import.meta.env.VITE_APP_PROXY_TIMEOUT) || 60000,
  // baseURL: '/api/v1',
  // timeout: 10000,
  headers: {
    'Content-Type': 'application/json, charset=utf-8'
  }
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    
    if (data.code === 200) {
      return data;
    } else  if (data.code === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    } else {
      // 业务错误
      ElMessage.error(data.message || '请求失败');
      return Promise.reject(new Error(data.message));
    }
  },
  (error) => {
    // HTTP错误
    if (error.response?.status === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足');
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误');
    } else {
      ElMessage.error(error.message || '网络错误');
    }
    
    return Promise.reject(error);
  }
);

export default request;